package com.earthea.common.algorithm.urlmatch;

import cn.hutool.core.util.ReUtil;
import com.earthea.common.algorithm.dictionarytree.DictionaryTreeAlgorithm;
import com.earthea.common.algorithm.dictionarytree.DictionaryTreeAlgorithmImpl;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.tuple.Pair;

import java.util.List;
import java.util.Locale;

/**
 * URL匹配字典树
 */
public class UrlMatchDictionaryTree implements UrlMatchAlgorithm<UrlMatchData> {

    private DictionaryTreeAlgorithm<Pair<String, String>, UrlMatchData> algorithm = new DictionaryTreeAlgorithmImpl<>(this::getUrlItems, this::isUrlVariable, () -> "{}");

    private List<String> getUrlItems(Pair<String, String> pair) {
        return Splitter.on("/").splitToList(pair.getLeft().toLowerCase(Locale.ENGLISH) + "/" + pair.getRight().replaceAll("\\?.*", "").replaceAll("/+", "/"));
    }

    private boolean isUrlVariable(String urlItem) {
        return ReUtil.isMatch(urlItem, "^\\{.+}$");
    }

    @Override
    public void addRule(String method, String url, boolean isPrefix, UrlMatchData data) {
        algorithm.addNode(Pair.of(method, url), isPrefix, data);
    }

    @Override
    public boolean isMatch(String method, String url) {
        return algorithm.isMatch(Pair.of(method, url));
    }

    @Override
    public UrlMatchData getMatchData(String method, String url) {
        return algorithm.getMatchData(Pair.of(method, url));
    }
}
